package cn.edu.zsc.rbac.dao.collection;

import cn.edu.zsc.rbac.dao.IBaseDao;
import cn.edu.zsc.rbac.domain.entity.BaseEntity;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * 数据访问层基类-基于容器存储数据
 *
**/
abstract class BaseDao<Entity extends BaseEntity> implements IBaseDao< Entity> {

    Map<Integer, Entity> data = new HashMap<>();

    private int idCounter=1;
    @Override
    public boolean existsById(int id) {
        return data.containsKey(id);
    }

    @Override
    public Entity findById(int id) {
        return data.get(id);
    }

    @Override
    public Collection<Entity> list() {
        return data.values();
    }

    @Override
    public Entity save(Entity entity) {
        Integer id = entity.getId();
        if (id == null) {
            id=idCounter++;
            entity.setId(id);
        }
        data.put(id, entity);
        return entity;
    }

    @Override
    public Entity delete(int id) {
        return data.remove(id);
    }
}
